package com.chery.media.ui.setting.wlan

import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.Utils
import com.chery.media.library.base.BaseViewModel
import com.chery.media.library.event.SingleLiveEvent
import com.chery.media.library.extend.livedata.BooleanLiveData
import com.chery.media.library.extend.loge
import com.chery.media.library.extend.toJson
import com.chery.media.library.extend.toast
import com.chery.media.library.wlan.IWifi
import com.chery.media.library.wlan.Wifi
import com.chery.media.library.wlan.WifiManager
import com.chery.media.utils.WifiManagerHelper

class WlanViewModel : BaseViewModel() {

    val currentWifi = SingleLiveEvent<Wifi>()

    val wlans = SingleLiveEvent<ArrayList<Wifi>>()

    var isConnectWifi = false

    override fun onCreate(owner: LifecycleOwner) {
        getWifiList()
    }

    private fun getWifiList() {
        WifiManager.create(Utils.getApp()).setOnWifiConnectListener {
            isConnectWifi = it
            if (isConnectWifi.not()) {
                if (currentWifi.value?.SSID().isNullOrEmpty().not() || currentWifi.value?.name().isNullOrEmpty().not()) {
                    WifiManager.create(Utils.getApp()).removeWifi(currentWifi.value)
                    currentWifi.postValue(Wifi())
                }
            }
            WifiManager.create(Utils.getApp()).scanWifi()
        }
        WifiManager.create(Utils.getApp()).setOnWifiChangeListener { wifis ->
            var connectWifiIndex = -1
            wifis.forEachIndexed { index, iWifi ->
                if (iWifi.isConnected && isConnectWifi) {
                    connectWifiIndex = index
                    currentWifi.postValue(iWifi as Wifi?)
                    return@forEachIndexed
                }
            }
            if (connectWifiIndex != -1) {
                wifis.removeAt(connectWifiIndex)
            }
            wlans.postValue(wifis as ArrayList<Wifi>?)
        }
    }

    fun openWlan() {
        WifiManager.create(Utils.getApp()).openWifi()
        WifiManager.create(Utils.getApp()).scanWifi()
    }

    fun closeWlan() {
        WifiManager.create(Utils.getApp()).closeWifi()
        currentWifi.postValue(Wifi())
        wlans.postValue(arrayListOf())
    }

    /**
     * 连接wifi
     */
    fun connectWlan(wifi: IWifi, password: String = "") {
        val isConnected = when {
            wifi.isEncrypt -> {
                WifiManager.create(Utils.getApp()).connectEncryptWifi(wifi, password)
            }

            wifi.isSaved -> {
                WifiManager.create(Utils.getApp()).connectSavedWifi(wifi)
            }

            else -> {
                WifiManager.create(Utils.getApp()).connectOpenWifi(wifi)
            }
        }
        if (isConnected) {
            "连接成功".toast()
            getWifiList()
        } else "连接失败".toast()
    }

    override fun onCleared() {
        super.onCleared()
        WifiManager.create(Utils.getApp()).destroy()
    }

}